<?php

namespace app\middleware;


class IpCheck
{
    public function handle($request, \Closure $next)
    {
        if($request->isPost()){
            $ip_check = env('ip.ip_check',true);
            if ($ip_check) {
                $client_ip = request()->ip();
                $ip_lists = IpWhiteList::where(['status'=>1])->column('ip');
                if (!$ip_lists) {
                    return json(['err_code' => -1, 'message' => 'IP白名单未设置'],400);
                }
                $ipWhiteTable = $this->getAllWhiteIp($ip_lists);

                if (!$this->checkIp($client_ip,$ipWhiteTable)){
                    return json(['err_code' => -1, 'message' => 'IP限制访问'],400);
                }
            }
        }
        return $next($request);
    }

    /**
     * 检查ip是否存在白名单内
     * @param $ip
     * @return bool
     */
    private function checkIp($ip,$ipWhiteTable){
        $isWhite = false;
        foreach($ipWhiteTable as $value) {
            if (preg_match("{$value}",$ip)) {
                $isWhite = true;
                break;
            }
        }
        return $isWhite;
    }

    private function getAllWhiteIp($ip_lists){
        foreach ($ip_lists as $ip) {
            $ip = str_ireplace(".","\.",$ip);
            $ip = str_replace("*","[0-9]{1,3}",$ip);
            $ip_list[] = "/^".$ip."$/";
        }
        return $ip_list;
    }
}